#include <map>
#include <string>
#include <vector>
#include <iostream>
#include <stdio.h>
#include "../include/mosdk.h"
#include <windows.h>

static int run_main(int argc, char* argv[]);

void split(std::vector<std::string>& result, std::string const &strTarget, char spliter)  
{
	result.clear();
	if(strTarget.empty())
		return;
	std::string::size_type offset(0), startPos(0);
	do
	{
		offset = strTarget.find(spliter, startPos) - startPos;
		if (offset == 0)
		{
			++startPos;
			continue;
		}
		result.push_back(strTarget.substr(startPos, offset));
		startPos += offset+1;
	}
	while (startPos);
}

int run_main(int argc, char* argv[])
{
	MOCLIENT* client = MOCreateClient("http://gamemake.sinaapp.com/mocool/api", ".php");

	bool ret;
	switch(argc)
	{
	case 1:
		ret = MOLoginByDeviceID(client);
		break;
	case 2:
		ret = MOLoginByToken(client, argv[1]);
		break;
	case 3:
		ret = MOLoginByUsername(client, argv[1], argv[2]);
		break;
	default:
		return -1;
	}
	if(!ret)
	{
		MODestoryClient(client);
		printf("MOLogin return false\n");
		return -1;
	}
	while(MOCLIENTSTATE_LOGINING==MOGetClientState(client)) Sleep(50);
	switch(MOGetClientState(client))
	{
	case MOCLIENTSTATE_AUTH:
		printf("MOLogin done\n");
		break;
	case MOCLIENTSTATE_FAILED:
	default:
		MODestoryClient(client);
		printf("MOLogin failed\n");
		return -1;
	}
	printf("token=%s\n", MOGetSessionKey(client));

	std::string line;
	for(;;)
	{
		std::cout<<"#";
		std::cin>>line;
		if(line=="quit") break;

		std::map<std::string, std::string> params;
		std::string method;

		size_t pos = line.find('?');
		if(pos==-1)
		{
			method = line;
		}
		else
		{
			method = line.substr(0, pos);
			line = line.substr(pos+1);

			std::vector<std::string> args;
			split(args, line, '&');
			for(size_t i=0; i<args.size(); i++)
			{
				pos = args[i].find('=');
				if(pos==-1)
				{
					printf("invalid line\n");
					continue;
				}
				else
				{
					std::string name = args[i].substr(0, pos);
					std::string value = args[i].substr(pos+1);
					if(name.empty() || value.empty())
					{
						printf("invalid line\n");
						continue;
					}
					params[name] = value;
				}
			}
		}

		MOREQUEST* request = MOClientRequestString(client, method.c_str(), params);
		while(MOREQUESTSTATE_PENDING==MORequestStatus(request)) Sleep(50);
		if(MOREQUESTSTATE_FAILED==MORequestStatus(request))
		{
			printf("request failed\n");
			MORequestDestory(request);
			continue;
		}
		printf("%s\n", MORequestGetResult(request));
		MORequestDestory(request);
	}

	MOLogout(client);
	MODestoryClient(client);
	return 0;
}

int main(int argc, char* argv[])
{
	MOInit("test");
	int ret = run_main(argc, argv);
	MOFini();
	return ret;
}
